package com.mv.springmvc.controller;

import com.mv.spring.bean.AutoWired;
import com.mv.spring.web.mvc.Controller;
import com.mv.spring.web.mvc.RequestMapping;
import com.mv.springmvc.pojo.User;
import com.mv.springmvc.service.UserService;
import com.mv.springmvc.view.View;
import com.mv.webserver.http.HttpRequest;
import com.mv.webserver.http.HttpResponse;
import com.mv.webserver.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@Controller
public class UserController extends HttpServlet {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    
    @AutoWired
    public UserService userService; 

    @RequestMapping("/reg")
    public void reg(HttpRequest request, HttpResponse response) {
        log.info("RegServlet.");
    }
    
    
    //使用内部tomcat实现时调用方法
    @RequestMapping("/list")
	public void list6(HttpRequest request, HttpResponse response) {

	       log.info("UserListServlet start.."  + this.toString());

    	   Context context = new Context();
	       try {
	    	   List<User> list =  userService.list();
		       context.setVariable("users",list);
	        } catch (Exception e) {
	        	e.printStackTrace();
	            log.error(e.getMessage(),e);
	        }
	       
	       String html = View.show("webapps/myweb/userList.html",context);
	        try {
	            response.setData(html.getBytes("UTF-8"));
	            response.putHeader("Content-Length","text/html");
	        } catch (UnsupportedEncodingException e) {
	            log.error(e.getMessage(),e);
	        }
	        log.info("UserListServlet end");
		
	}

  //使用外部tomcat实现时调用方法
    @RequestMapping("/list2")
	public String list(ServletRequest request, ServletResponse response) {
	       log.info("UserListServlet start..");
	       List<User> list =  userService.list();
	
	       Context context = new Context();
	       context.setVariable("users",list);
	       String html = View.show("webapps/myweb/userList.html",context);
	       response.setCharacterEncoding("UTF-8");
	        log.info("UserListServlet end");	
	       return html;	
    }
    
	public void list() {
		 log.info("UserListServlet start.."  + this.toString());
	       List<User> list =  userService.list();
	        log.info("list to string" + list.toString());	
    }


	
}
